package org.cyx.javasx.view;

import java.awt.LayoutManager;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;

import java.awt.Component;
import java.awt.Container;

public class ViewContainer extends View implements IContainer {
    public List<Component> childrenView = new ArrayList<>();

    public ViewContainer(Container container) {
        super(container);
    }

    /* @Override
    public Object findViewById(String id) {
        Object view = null;
        if (this.id != null && this.id.equals(id)) {
            view = this.getOComponent();
        } else if (childrenView.size() > 0) {
            for (Component component : childrenView) {
                if ((view = this.findViewById(id, component)) != null) {
                    break;
                }
            }
        }
        return view;
    } */

    @Override
    public Object findViewById(String id) {
        if(this.id != null && this.id.equals(id)){
            return this.component;
        }else{
            return findViewById(id, this.component);
        }
    }

    protected Object findViewById(String id, Component parentComponent) {
        Object obj = null;
        if (parentComponent instanceof Container) {
            Container jcom = (Container) parentComponent;
            Component[] coms = jcom.getComponents();
            for (Component component : coms) {
                if(component instanceof IView){
                    // 减少递归操作，应该优化成不使用递归性能会好一些
                    obj = ((IView)component).findViewById(id);
                } else {
                    obj = this.findViewById(id, component);
                }
                if(obj != null){
                    break;
                }
            }
        }
        return obj;
    }

    @Override
    public void addView(Component component, LayoutManager layoutManager) {
        Container thisContainer = (Container) this.component;
        thisContainer.add(component, layoutManager);
        this.childrenView.add(component);
        thisContainer.revalidate();
    }

    @Override
    public void updateViewLayout(Component component, LayoutManager layoutManager) {
        // TODO Auto-generated method stub

    }

    @Override
    public void removeView(Component component) {
        Container thisContainer = (Container) this.component;
        if (childrenView.contains(component)) {
            thisContainer.remove(component);
            this.childrenView.remove(component);
            thisContainer.revalidate();
        } else {
            for (Component view : childrenView) {
                if (view instanceof IContainer) {
                    ((IContainer) view).removeView(view);
                }
            }
        }
    }
}